package com.example.controller;

/**
 * com.example.controller.ProductController
 *
 * @author ZRS
 * @version V1.0
 * @since 2025/11/1 00:27
 */

import com.example.index.Product;
import com.example.service.ElasticsearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/products")
public class ProductController {

    @Autowired
    private ElasticsearchService elasticsearchService;

    // 创建索引
    @PostMapping("/index/create")
    public boolean createIndex() {
        return elasticsearchService.createIndex();
    }

    // 添加产品
    @PostMapping
    public Product addProduct(@RequestBody Product product) {
        return elasticsearchService.saveProduct(product);
    }

    // 根据ID获取产品
    @GetMapping("/{id}")
    public Product getProduct(@PathVariable String id) {
        return elasticsearchService.getProductById(id);
    }

    // 搜索产品
    @GetMapping("/search")
    public List<Product> searchProducts(@RequestParam String keyword) {
        return elasticsearchService.searchProducts(keyword);
    }

    // 价格范围搜索
    @GetMapping("/search/price")
    public List<Product> searchByPrice(@RequestParam double min, @RequestParam double max) {
        return elasticsearchService.searchByPriceRange(min, max);
    }

    // 删除产品
    @DeleteMapping("/{id}")
    public void deleteProduct(@PathVariable String id) {
        elasticsearchService.deleteProductById(id);
    }

    // 分页查询
    @GetMapping("/searchProductsWithPage")
    public List<Product> searchProductsWithPage(@RequestParam String keyword, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int size) {
        return elasticsearchService.searchProductsWithPage(keyword, page, size);
    }
}